package com.example.casper.Experiment2024.data;
import static java.lang.System.in;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class DataBank {

    private final Context context;
    private final String dataFile_name = "travel_records.data";

    public DataBank(Context context) {
        this.context = context.getApplicationContext();
    }

    public ArrayList<TravelRecord> readTravelRecords() {
        ArrayList<TravelRecord> records = new ArrayList<>();
        File file = new File(context.getFilesDir(), dataFile_name);

        // 检查文件是否存在
        if (file.exists()) {
            try {
                FileInputStream fileIn = context.openFileInput(dataFile_name);
                 // 创建一个对象输入流
                ObjectInputStream in = new ObjectInputStream(fileIn);

                // 从输入流中读取对象
                records = (ArrayList<TravelRecord>) in.readObject();

                // 关闭输入流
                in.close();

                // 关闭文件输入流
                fileIn.close();


        } catch (IOException | ClassNotFoundException e) {
            Log.e("Experiment2024.data", "Error reading travel records", e);
            }

        }
        return records;
    }

    public void saveItems(ArrayList<TravelRecord> tripRecordActivities) {
        FileOutputStream fileOut = null;
        try {
            fileOut = context.openFileOutput(dataFile_name, Context.MODE_PRIVATE);
            // 创建一个对象输出流
            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            // 将对象写入输出流
            out.writeObject(tripRecordActivities);

            // 关闭输出流
            out.close();

            fileOut.close();
        } catch (IOException e) {
            Log.e("Experiment2024.data", e.toString());
        }

    }

}





